<template>
	<uv-picker ref="picker"
	 :columns="list" 
	 :keyName="keyName" 
	 :closeOnClickOverlay="false"
	 :defaultIndex="defaultIndex"
	 :confirmText="confirmText" 
	 :cancelText="cancelText" 
	 @confirm="confirm" 
	 @cancel="cancel"></uv-picker>
</template>

<script setup>
	const picker = ref(null)
	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		},
		list: {
			type: Array,
			default: () => []
		},
		keyName:{
			type:String,
			default:'name'
		},
		valueName:{
			type:[String,Number],
			default:''
		},
		keyValue:{
			type:String,
			default:'id'
		},
		confirmText:{
			type:String,
			default:'确定'
		},
		cancelText:{
			type:String,
			default:'取消'
		},
	})
	const defaultIndex = computed(() => {
		let list = props.list[0]
		let valueIndex = list.findIndex(item => item[props.keyValue] == props.valueName)
		// console.log(props.keyValue,props.valueName);
		return [valueIndex]
	})
	const emit = defineEmits(['update:modelValue','update:valueName','confirm','cancel'])
	watch(() => props.modelValue,(value) => {
		emit('update:modelValue',value)
		if(value) picker.value.open()
		else picker.value.close()
	})
	function cancel(){
		emit('update:modelValue',false)
		emit('cancel')
	}
	function confirm(e){
		let selectValue = ''
		if(!e.value[0]) selectValue = props.list[0][0][props.keyValue]
		else selectValue = e.value[0][props.keyValue]
		// return console.log(selectValue,props.list);
		emit('update:modelValue',false)
		emit('update:valueName',selectValue)
		emit('confirm',selectValue,e)
	}
</script>

<style>

</style>